package com.huiminpay.merchant.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.huiminpay.common.cache.domain.BusinessException;
import com.huiminpay.common.cache.domain.CommonErrorCode;
import com.huiminpay.common.cache.domain.PageVO;
import com.huiminpay.merchant.api.IStoreService;
import com.huiminpay.merchant.covert.StoreCovert;
import com.huiminpay.merchant.dto.QueryStoreDTO;
import com.huiminpay.merchant.dto.StoreDTO;
import com.huiminpay.merchant.entity.Store;
import com.huiminpay.merchant.mapper.StoreMapper;

import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;


@Service
public class IStoreServiceImpl implements IStoreService {

    @Autowired
    StoreMapper storeMapper;


    @Override
    public PageVO<StoreDTO> queryStoreByPage(QueryStoreDTO queryStoreDTO) {

        //使用mybatis plus的分页
        IPage<Store> iPage = new Page<>(queryStoreDTO.getPageNo(),queryStoreDTO.getPageSize());
        //根据商户ID 作为查询条件
        QueryWrapper<Store> qw = new QueryWrapper<>();
        qw.lambda().eq(Store::getMerchantId,queryStoreDTO.getMerchantId());
        //分页查询
        IPage<Store> storeIPage = storeMapper.selectPage(iPage, qw);
        //结果集进行转换
        List<Store> stores = storeIPage.getRecords();

        PageVO<StoreDTO> storeDTOS = new PageVO<>();
        storeDTOS.setPage(queryStoreDTO.getPageNo());
        storeDTOS.setPageSize(queryStoreDTO.getPageSize());
        storeDTOS.setCounts(storeIPage.getTotal());
        storeDTOS.setItems(StoreCovert.INSTANCE.entity2dtoList(stores));
        return storeDTOS;
    }

    @Override
    public StoreDTO queryById(Long storeId) {


        QueryWrapper<Store> qw = new QueryWrapper<>();
        qw.lambda().eq(Store::getId,storeId);
        Store store = storeMapper.selectOne(qw);

        return StoreCovert.INSTANCE.entity2dto(store);
    }

    @Override
    public void addAddress(StoreDTO storeDTO) {

        if (storeDTO.getId() == null){
            throw new BusinessException(CommonErrorCode.E_300002);
        }

        storeDTO.setMerchantId(null);
        storeDTO.setParentId(null);
        storeDTO.setStoreStatus(null);

        Store store = StoreCovert.INSTANCE.dto2entity(storeDTO);

        storeMapper.updateById(store);

    }
}
